package com.fox.moon.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.fox.moon.mapper.LoginIInfoMapper;
import com.fox.moon.pojo.LoginInfo;
import com.fox.moon.pojo.ResultEntity;
import com.fox.moon.pojo.SmsSendRequest;
import com.fox.moon.util.JsonUtil;
import com.fox.moon.util.SendMsg;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/api")
public class LoginInfoController {
    public static final String charset = "utf-8";
    public static String smsSingleRequestServerUrl = "http://smssh1.253.com/msg/send/json";
    public static String report= "true";
    // 用户平台API账号(非登录账号,示例:N1234567)
    public static String account = "YZM0547017";
    // 用户平台API密码(非登录密码)
    public static String pswd = "4du59iqrmO8b7d";
    private final LoginIInfoMapper mapper;

    public LoginInfoController(LoginIInfoMapper mapper) {
        this.mapper = mapper;
    }

    @GetMapping("/getCode")
    public String getCodeByPhone(String phone){
        QueryWrapper<LoginInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("user_phone",phone);
        String code = (int) ((Math.random() * 9 + 1) * 100000) + "";
        String msg = "【SunVanAi】您本次的登录验证码为"+code+",验证码有限期为5分钟。";
        LoginInfo loginInfo = new LoginInfo();
        loginInfo.setLoginDate(new Date());
        loginInfo.setUserPhone(phone);
        loginInfo.setPhoneCode(code);
        LoginInfo loginInfo1 = mapper.selectOne(wrapper);
        if (loginInfo1 != null) {
            UpdateWrapper<LoginInfo> updateWrapper = new UpdateWrapper<>();
            updateWrapper.set("phone_code",code)
                    .eq("user_phone",phone);
            mapper.update(null, updateWrapper);
        }else{
            mapper.insert(loginInfo);
        }
        SmsSendRequest smsSingleRequest = new SmsSendRequest(account, pswd, msg, phone,report);
        String requestJson = JSON.toJSONString(smsSingleRequest);
        String response = SendMsg.sendSmsByPost(smsSingleRequestServerUrl, requestJson);
        System.out.println(response);

        return JsonUtil.getBeanToString(ResultEntity.success(200,"get success"));
    }

    @GetMapping("/login")
    public String login(String phone,String code){
        QueryWrapper<LoginInfo> query = new QueryWrapper<>();
        query.eq("user_phone",phone);
        List<LoginInfo> loginInfos = mapper.selectList(query);
        boolean equals = loginInfos.get(0).getPhoneCode().equals(code);
        if (equals){
            return JsonUtil.getBeanToString(ResultEntity.success(200,"success"));
        }
        return JsonUtil.getBeanToString(ResultEntity.failed(201, "验证码不正确"));
    }
}
